const { ProjectImage } = require('../models/Middle')
const moment = require('moment')
const util = require('../utils/util')
const path = require('path')
const fs = require('fs')

// 新增
async function add (projectImage, file, uid) {
  projectImage.name = '临时'
  projectImage.ctime = moment().format('YYYY-MM-DD HH:mm:ss')
  projectImage.mtime = moment().format('YYYY-MM-DD HH:mm:ss')
  try {
    const res = await ProjectImage.create(projectImage)
    let data = util.uploadPro(path.join('/project', uid, 'image'), file, res.id)
    await ProjectImage.update({
      path: data.path,
      name: data.name
    }, {
      where: {
        id: res.id
      }
    })
    return await ProjectImage.findOne({
      where: {
        id: res.id
      }
    })
  } catch (error) {
    throw error
  }
}

// 查询（分页、排序、模糊查询搜索、查询状态）
/**
 * limit 提取多少行，offset 跳过多少行
 * @param {*} page 当前页码
 * @param {*} size 每页条数
 */
async function findAll (query) {
  try {
    const { count, rows } = await ProjectImage.findAndCountAll({
      include: {
        all: true
      },
      where: {
        pid: query.pid
      },
      order: [
        ['ctime','desc']
      ]
    })
    rows.forEach(item => {
      item.path = fs.readFileSync(path.join(__dirname, '../', item.path)).toString('base64')
    })
    return {
      count,
      data: rows
    }
  } catch (error) {
    throw error
  }
}

// 修改
async function update (projectImage) {
  projectImage.mtime = moment().format('YYYY-MM-DD HH:mm:ss')
  try {
    return await ProjectImage.update(projectImage, {
      where: {
        id: projectImage.id
      }
    })
  } catch (error) {
    throw error
  }
}

// 删除
async function deleteById (id) {
  try {
    // 删除数据库中本条数据，再删除相关图片文件
    const res = await ProjectImage.findOne({
      where: {
        id
      }
    })
    fs.unlink(path.join(__dirname, '../', res.path), async err => {
      if (err) throw err
      return await ProjectImage.destroy({
        where: {
          id
        }
      })
    })
  } catch (error) {
    throw error
  }
}

// 根据id查询
async function findOneById (id) {
  try {
    return await ProjectImage.findOne({
      include: {
        all: true
      },
      where: {
        id
      }
    })
  } catch (error) {
    throw error
  }
}

module.exports = {
  add,
  findAll,
  update,
  deleteById,
  findOneById
}